//
//  RegistViewController.m
//  Growth
//
//  Created by MEET on 12-1-4.
//  Copyright 2012 MEETStudio. All rights reserved.
//

#import "RegistViewController.h"

#import "RegexKitLite.h"

#import "NotificationEngine.h"

static WebConnectionArray *verifyNickName_connection;
static WebConnectionArray *verifyEmail_connection;
static WebConnectionArray *emailRegiete_connection;

static ASIHTTPConnection *regist_connect;

@implementation RegistViewController

@synthesize nickNametextField;
@synthesize emailtextField;
@synthesize keytextField;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

//*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
    [nickNametextField setFrame:CGRectMake(nickNametextField.frame.origin.x, nickNametextField.frame.origin.y, nickNametextField.frame.size.width, 35)];
    
    [emailtextField setFrame:CGRectMake(emailtextField.frame.origin.x, emailtextField.frame.origin.y, emailtextField.frame.size.width, 35)];
    
   [keytextField setFrame:CGRectMake(keytextField.frame.origin.x, keytextField.frame.origin.y, keytextField.frame.size.width, 35)];
	   
    //定义返回按钮
    UIBarButtonItem * backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: @"返回" style:UIBarButtonSystemItemDone target:self action: nil];   
    
    [[self navigationItem] setBackBarButtonItem:backBarButtonItem]; 
    self.navigationItem.title = @"注册";
    
    [backBarButtonItem release]; 

    
    [super viewDidLoad];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[nickNametextField release];
	[emailtextField release];
	[keytextField release];
    
    if (regist_connect != nil) {
        regist_connect.connectionDelegate = nil;
        [regist_connect release];
        regist_connect = nil;
    }
    
    if (verifyEmail_connection != nil) {
        verifyEmail_connection.connectionDelegate = nil;
        [verifyEmail_connection release];
        verifyEmail_connection = nil;
    }
    if (verifyNickName_connection != nil) {
        verifyNickName_connection.connectionDelegate = nil;
        [verifyNickName_connection release];
        verifyNickName_connection = nil;
    }
    
    if (emailRegiete_connection != nil) {
        emailRegiete_connection.connectionDelegate = nil;
        [emailRegiete_connection release];
        emailRegiete_connection = nil;
    }
    [super dealloc];
}


#pragma textField delegat
-(void)textFieldDidBeginEditing:(UITextField *)textField{
 
//    if (textField.tag == 2) {
//        [self verifyNickName:nickNametextField.text];
//    }
//    if (textField.tag == 3) {
//        [self verifyEmail:emailtextField.text];
//    }
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
//    if (textField.tag ==1) {
//        [self verifyNickName:nickNametextField.text];
//    }
//    if (textField.tag == 2) {
//        [self verifyEmail:emailtextField.text];
//    }
    
    
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (textField.tag == 1) {
        [emailtextField becomeFirstResponder];
    }
    if (textField.tag == 2) {
        [textField resignFirstResponder];
    }
    if (textField.tag == 3) {
        //[self registerAction:nil];
        [textField resignFirstResponder];
    }
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField.tag == 1) {
        CLog(@"nickname change!");
        _isNickNameCorrect = NO;
    }
    if (textField.tag == 2) {
        CLog(@"email change!");
        _isEmailCorrect = NO;
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.tag == 1) {
        CLog(@"nickname change!");
        _isNickNameCorrect = NO;
    }
    if (textField.tag == 2) {
        CLog(@"email change!");
        _isEmailCorrect = NO;
    }

    
    return YES;
}

- (IBAction)emailChange:(id)sender
{
    CLog(@"email change!");
    _isEmailCorrect = NO;  
}

- (IBAction)nickNameChange:(id)sender
{
    CLog(@"nickname change!");
    _isNickNameCorrect = NO;
}


#pragma verify

-(void)verifyNickName:(NSString *)nickName{ //验证nickname
    
    _isNickNameCorrect = NO;
    if (NETWORK_STATUS_LOADING) {
        NSMutableURLRequest *request = [WebRequest verifyNickNameRequest:nickName];
        
        CLog(@"request %@", request);
        if (verifyNickName_connection != nil) {
            verifyNickName_connection.connectionDelegate = nil;
        }
        verifyNickName_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
    }

    
}

-(void)verifyEmail:(NSString *)email{
    
    
    _isEmailCorrect = NO;
    if (NETWORK_STATUS_LOADING) {
        NSMutableURLRequest * request = [WebRequest verifyEmailRequest:email];
        
        CLog(@"request %@", request);
        if (verifyEmail_connection != nil) {
            verifyEmail_connection.connectionDelegate = nil;
        }
        verifyEmail_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
    }

    
}

#pragma mark -WebConnection delegate

- (void)connectionSuccess:(NSDictionary *)dict{
	
    
}

- (void)connectionError:(NSError *)error{
     [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求错误或超时！" duration:DEFAULT_LOADING_TIME *1.2];
	
}
- (void)postSuccess:(NSString *)postinfo{
    CLog(@"post info");
    
    
}

- (void)connectionArraySuccess:(NSDictionary *)dict connectionURL:(NSString *)url{
    
    
    CLog(@"Dict :%@", dict);
    
    NSRange range = [url rangeOfString:@"verify/account"]; 
    
    if (range.length > 0)  {
        
         CLog(@"verify email %@",[dict objectForKey:@"object"] );
        
       if ([[dict objectForKey:@"object"] boolValue]== TRUE) { 
           _isEmailCorrect = TRUE;       
           
           [self registerAccount];
           
            return;
        }
       else{
           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"邮箱错误" message:@"邮箱已注册或输入有误，请重试！" 
                                                          delegate:self 
                                                 cancelButtonTitle:@"确定" otherButtonTitles:nil];
           
           [alert show];
           [alert release];
       }

    }

    range = [url rangeOfString:@"verify/nickname"];
    if (range.length > 0)  {
        
        CLog(@"verify nickName %@",[dict objectForKey:@"object"] );
        
        if ([[dict objectForKey:@"object"] boolValue]== TRUE) { 
            _isNickNameCorrect = TRUE;       
            
            [self registerAccount];
            
            return;
        }
        else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"昵称错误" message:@"该昵称已经被注册啦，换一个吧！" 
                                                           delegate:self 
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [alert show];
            [alert release];
        }
        
        
    }

    
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/openmobile/user/regist",UCENTERBASEURL]])  {
        
        if([dict objectForKey:@"object"]){
            
            NSDictionary *userInfo = [dict objectForKey:@"object"];
            
            NSInteger errorCode = [[userInfo objectForKey:@"errorCode"] intValue];
            
            if((errorCode == 0 || errorCode == 6) &&[[userInfo allKeys] containsObject:@"userId"]){
    
    
            [[NSUserDefaults standardUserDefaults] setValue:[userInfo objectForKey:@"userId"] forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults]setValue:[userInfo objectForKey:@"userNickname"] forKey:@"userName"];
            [[NSUserDefaults standardUserDefaults]setValue:[userInfo objectForKey:@"userAttachmentId"] forKey:@"userAttachmentId"];
            
            [[NSUserDefaults standardUserDefaults] setValue:[userInfo objectForKey:@"Ucenter-Code"] forKey:@"Ucenter-Code"];
            [[NSUserDefaults standardUserDefaults] setValue:[userInfo objectForKey:@"Ucenter-VerifyCode"] forKey:@"Ucenter-VerifyCode"];
            
            [[NotificationEngine sharedNotificationEngine] postDeviceToken];
            [self registerSuccess ];
            }
            else {
                NSString *errorReason = [userInfo objectForKey:@"errorReason"];
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"注册错误" message:errorReason delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                
                [alertView show];
                [alertView release];
            }

        }
        
    }
    
       
    
}

- (void)connectionArrayError:(NSError *)error{
    
    
    [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求错误或超时！" duration:DEFAULT_LOADING_TIME];

	
}



#pragma mark action

- (void)registerSuccess{
	//注册成功，返回登陆界面，并考虑直接跳转登陆 
	
    [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:REGIST_LOGIN_KEY];
    
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:1] forKey:@"isFirstInApp"];
    
    
    NSString *uidStr = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] stringValue];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: uidStr, @"uid", nil];
    [MobClick event:MobClick_Register_Email attributes:dict];
    
    
    [self.navigationController dismissModalViewControllerAnimated:YES];
    
    
}

- (void)registerError{
	//弹出错误提示
}


- (void)registerAccount
{
    
    if (_isNickNameCorrect && _isEmailCorrect ) {
        
        if (NETWORK_STATUS_LOADING) {
            
            
            NSArray *keys = [NSArray arrayWithObjects:@"appId",@"account",@"nickname", nil];
            
            
            NSArray *objects;
            objects = [NSArray arrayWithObjects:[NSNumber numberWithInt:APP_ID],emailtextField.text,nickNametextField.text, nil];
            
            NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
            
            NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
            CLog(@"theBodyString  %@", theBodyString);
            
            
            NSData *jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
            
            NSMutableURLRequest * request = [WebRequest registRequestWith:jsonData];
            
            CLog(@"request %@", request);
            if (emailRegiete_connection != nil) {
                emailRegiete_connection.connectionDelegate = nil;
            }
            emailRegiete_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
            
            
            _isPostRegist = TRUE;
        }
 
    }
    
}
 
-(IBAction)registerAction:(id)sender{

    if (emailtextField.text == nil || emailtextField.text.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"邮箱不能为空"
							  
													   delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
		[alert show];
        [alert release];
        return;

    }
    if (nickNametextField.text == nil || nickNametextField.text.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"用户名不能为空"
							  
													   delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
		[alert show];
        [alert release];
        return;

    }
    
    
    [LoadingView showDefaultLoadingView];
    

    [nickNametextField resignFirstResponder];
    [emailtextField resignFirstResponder];
    [keytextField resignFirstResponder];
   
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileUser/MobileRegisterAction.aspx",BASEURL];
    
	NSURL *url = [NSURL URLWithString:urlString];
   
    NSArray *keys = [NSArray arrayWithObjects:@"UserName",@"Password",@"PrivateEmail", nil];
    
    NSArray *objects = [NSArray arrayWithObjects:nickNametextField.text,keytextField.text,emailtextField.text, nil];
    
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    CLog(@"theBodyString  %@", theBodyString);
    
    //  //
    NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    if (regist_connect != nil) {
        regist_connect.connectionDelegate = nil;
        [regist_connect release];
        regist_connect = nil;
    }

    
     regist_connect = [[ASIHTTPConnection alloc] initPOSTWithURL:url jsonData:_jsonData];
    regist_connect.connectionDelegate = self;
    
    [regist_connect startAsynchronous];


}

#pragma mark conneciton delegate
- (void)requestFinished:(ASIHTTPConnection *)connection resultDict:(NSDictionary *)dict URL:(NSURL *)url info:(NSDictionary *)info{
    
    CLog(@"dict = %@",dict);
    
    [LoadingView hideWithAnimated:YES];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"返回的数据" message:[NSString stringWithFormat:@"%@",[dict objectForKey:@"messageContent"]]
                          
                                                   delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil];
    [alert show];
    [alert release];

}

- (void)requestFailed:(ASIHTTPConnection *)connection error:(NSError *)error URL:(NSURL *)url info:(NSDictionary *)info{
    
    [LoadingView hideWithAnimated:YES];
    CLog(@"connectino Erro");
}






-(IBAction)backgroundTap:(id)sender{
	[nickNametextField resignFirstResponder];
	[emailtextField resignFirstResponder];
	[keytextField resignFirstResponder];
}

@end
